import { getUserInfoAPI } from "@/api/user";
import { userInfoType } from "@/types/user";
import { playerResponseType, voteListResponseType } from "@/types/vote";
import { defineStore } from "pinia";
import { ref } from "vue";

export const useUserStore = defineStore(
  "user",
  () => {
    const token = ref<string>();
    const username = ref<string>();
    const userInfo = ref<userInfoType>();
    const selectedVote = ref<voteListResponseType>();
    const selectedPlayer = ref<playerResponseType>();

    // 保存会员信息，登录时使用
    const setUserInfo = async () => {
      const res = await getUserInfoAPI();
      userInfo.value = res.data;
    };

    // 清理会员信息，退出时使用
    const clearUserInfo = () => {
      userInfo.value = undefined;
      token.value = undefined;
      username.value = undefined;
    };

    // 记得 return
    return {
      token,
      username,
      setUserInfo,
      clearUserInfo,
      userInfo,
      selectedVote,
      selectedPlayer,
    };
  },
  {
    // 网页端配置
    // persist: true,
    // 小程序端配置
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key);
        },
        setItem(key, value) {
          uni.setStorageSync(key, value);
        },
      },
    },
  }
);
